/**
 * 
 */
package com.tcl.wip.client.orm;

import java.util.LinkedList;
import java.util.List;

import com.tcl.wip.client.WipApp;
import com.tcl.wip.commons.utils.HttpClient;
import com.tcl.wip.commons.utils.JsonParser;

/**
 * @author zhaowen.zhuang
 * @Date Jan 23, 2015
 */
public class WipSequenceIdGenerater implements IdGenerator<Long> {

    private String sequenceUrl;
    private String tableName;
    private int fetchCount = 100;

    private LinkedList<Long> cachedIds = new LinkedList<>();

    /**
     * @param app
     * @param tableName
     */
    public WipSequenceIdGenerater(WipApp app, String tableName) {
        this.tableName = tableName;
        this.sequenceUrl =
                app.getServer() + "/app/" + app.getAppId() + "/table/" + this.tableName
                        + "/generateIds?count=" + this.fetchCount;
    }

    @Override
    public synchronized Long generate() {
        if (this.cachedIds.size() == 0) {
            fetchIds();
        }
        return cachedIds.removeLast();
    }

    private void fetchIds() {
        String json = HttpClient.doGet(sequenceUrl);
        List<Long> ids = JsonParser.parseParametricType(json, List.class, Long.class);
        for (Long id : ids) {
            cachedIds.push(id);
        }
    }

}
